package com.passion.filter;

import cn.hutool.core.util.IdUtil;
import com.passion.common.util.StringUtils;
import com.passion.context.UserContext;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 建类说明：MDC过滤器
 *
 * @author 中国印
 * @since 2023年03月06日 22:43:44
 */
@Component
@Order(2)
public class MdcFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session != null) {
            // 会话有效的情况下才设置
            String userId = UserContext.getUserId();
            String requestId = request.getParameter("requestId");
            if (StringUtils.isBlank(requestId)) {
                requestId = IdUtil.simpleUUID();
            }
            // 设置MDC，让打印的日志中显示用户ID和请求ID，便于追踪
            MDC.put("userId", userId);
            MDC.put("requestId", requestId);
            try {
                filterChain.doFilter(request, response);
            } finally {
                MDC.clear();
            }
        }
    }
}
